package com.shuwen.gcdj.common.config.webSocket;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shuwen.gcdj.common.constant.Constants;
import com.shuwen.gcdj.common.util.crypt.JWTUtil;
import com.shuwen.gcdj.entity.Account;
import com.shuwen.gcdj.mapper.mysql.AccountMapper;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import java.util.Map;


/**
 * @author XYC
 */
@Component
public class WebSocktToken implements HandshakeInterceptor {

    @Resource
    private AccountMapper accountMapper;
    /**
     * 连接之前，若返回false，则不建立链接 *
     *
     * @param request
     * @param response
     * @param wsHandler
     * @param attributes
     * @return
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse
            response, WebSocketHandler wsHandler, Map<String, Object> attributes) {
        //将用户id放入socket处理器的会话(WebSocketSession)中
        ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
        HttpHeaders headers = request.getHeaders();
        //获取参数
        String token = serverHttpRequest.getServletRequest().getParameter("eceibstoken");
        String uid= JWTUtil.getUserId(token);
        attributes.put("id", uid);
        Account user=  accountMapper.selectOne(new QueryWrapper<Account>().lambda()
                .eq(Account::getIsDelete, Constants.IS_DELETE_NORMAL)
                .eq(Account::getId, uid));
        //可以在此处进行权限验证，当用户权限验证通过后，进行握手成功操作，验证失败返回false
        if (user==null) {
            System.out.println("用户验证失败.....");
            return false;
        }
        System.out.println("用户验证成功。。。。。。。");
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse
            response, WebSocketHandler wsHandler, Exception exception) {
        System.out.println("连接成功啦。。。。。。");
    }
}
